<template>
  <div id="manageQuestionView">
    <h2>管理题目</h2>
    <SearchQuestionVOView @getResult="getResult" />
    <a-divider size="0" />
    <a-table
      :columns="columns"
      :data="dataList"
      :pagination="{
        pageSize: searchParams.pageSize,
        current: searchParams.current,
        total,
        showTotal: true,
      }"
      @page-change="onPageChange"
    >
      <template #tags="{ record }">
        <a-space wrap>
          <a-tag v-for="(tag, index) of record.tags" :key="index" color="blue"
            >{{ tag }}
          </a-tag>
        </a-space>
      </template>
      <template #acceptedRate="{ record }">
        {{
          `${
            record.submitNum && record.submitNum > 0
              ? record.acceptedNum / record.submitNum
              : "0"
          }%（${record.acceptedNum} / ${record.submitNum}）`
        }}
      </template>
      <template #timeLimit="{ record }">
        {{ record.judgeConfig.timeLimit }}
      </template>
      <template #memoryLimit="{ record }">
        {{ record.judgeConfig.memoryLimit }}
      </template>
      <template #stackLimit="{ record }">
        {{ record.judgeConfig.stackLimit }}
      </template>
      <template #userName="{ record }">
        {{ record.userVO.userName }}
      </template>
      <template #createTime="{ record }">
        {{ moment(record.createTime).format("YYYY-MM-DD HH:ss:mm") }}
      </template>
      <template #optional="{ record }">
        <a-space>
          <a-button type="primary" @click="doUpdate(record)">修改</a-button>
          <a-button type="primary" status="danger" @click="doDelete(record)"
            >删除
          </a-button>
        </a-space>
      </template>
    </a-table>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref, watchEffect } from "vue";
import {
  Question,
  QuestionControllerService,
  QuestionQueryRequest,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import moment from "moment/moment";
import SearchQuestionVOView from "@/components/SearchQuestionVOView.vue";

const dataList = ref([]);
const total = ref(0);
const router = useRouter();

/**
 * 查询条件
 */
const searchParams = ref<QuestionQueryRequest>({
  title: "",
  tags: [],
  pageSize: 10,
  current: 1,
});

/**
 * 获取后端数据
 */
const loadData = async () => {
  const res = await QuestionControllerService.listQuestionVoByPageUsingPost(
    searchParams.value
  );
  if (res.code === 0) {
    dataList.value = res.data.records;
    total.value = res.data.total;
  } else {
    message.error("加载失败，" + res.message);
  }
};

/**
 * 当前页面数据有改动时，会刷新页面（监控 loadData 函数中的数据变化）
 */
watchEffect(() => {
  loadData();
});

/**
 * 页面初始化时会执行 onMounted 函数
 */
onMounted(() => {
  loadData();
});

// {id: "1690623426516860930", title: "A + D", content: "新的内容", tags: "["奥里给"]", answer: "新的答案",…}

const columns = [
  {
    title: "题号",
    dataIndex: "id",
    width: 150,
  },
  {
    title: "题目名称",
    dataIndex: "title",
    width: 100,
  },
  {
    title: "题目内容",
    dataIndex: "content",
    width: 200,
  },
  {
    title: "标签",
    slotName: "tags",
    width: 200,
  },
  {
    title: "答案",
    dataIndex: "answer",
    width: 100,
  },
  {
    title: "通过率（通过数 / 提交数）",
    slotName: "acceptedRate",
    width: 220,
  },
  {
    title: "判题配置",
    dataIndex: "judgeConfig",
    children: [
      {
        title: "时间限制（ms）",
        slotName: "timeLimit",
        width: 100,
      },
      {
        title: "内存限制（kb）",
        slotName: "memoryLimit",
        width: 100,
      },
      {
        title: "堆栈限制（kb）",
        slotName: "stackLimit",
        width: 100,
      },
    ],
  },
  {
    title: "用户id",
    dataIndex: "userId",
    width: 100,
  },
  {
    title: "创建用户",
    slotName: "userName",
    width: 100,
  },
  {
    title: "创建时间",
    slotName: "createTime",
    width: 170,
  },
  {
    title: "操作",
    slotName: "optional",
    width: 100,
  },
];

/**
 * 删除
 * @param question
 */
const doDelete = async (question: Question) => {
  const res = await QuestionControllerService.deleteQuestionUsingPost({
    id: question.id,
  });
  if (res.code === 0) {
    message.success("删除成功");
    // 更新数据
    loadData();
  } else {
    message.error("删除失败，" + res.message);
  }
};

/**
 * 修改
 * @param question
 */
const doUpdate = async (question: Question) => {
  router.push({
    path: "/update/question",
    query: {
      id: question.id,
    },
  });
};

const onPageChange = (page: number) => {
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

/**
 * 获取组件的结果并赋值
 */
const getResult = (title: string, tags: []) => {
  searchParams.value.title = title;
  searchParams.value.tags = tags;
  searchParams.value.current = 1;
  loadData();
};
</script>

<style scoped>
#manageQuestionView {
}
</style>
